<!DOCTYPE HTML>
<html>

<head>
	<meta charset="utf-8">
	<meta name="renderer" content="webkit|ie-comp|ie-stand">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport"
	      content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
	<meta http-equiv="Cache-Control" content="no-siteapp"/>
	<link href="${ctx}/css/font-awesome.min93e3.css?v=4.4.0" rel="stylesheet">
	<link href="${ctx}/css/plugins/iCheck/custom.css" rel="stylesheet">
	<link href="${ctx}/css/bootstrap.min14ed.css?v=3.3.6" rel="stylesheet">
	<link href="${ctx}/css/bootstrap-treeview.min.css" rel="stylesheet">
	<link href="${ctx}/css/style.min862f.css?v=4.1.0" rel="stylesheet">
	<![endif]-->
	<title>角色修改</title>
	<style>
		input.error {
			background: rgb(251, 227, 228);
			border: 1px solid #fbc2c4;
			color: red;
		}

		label.error {
			color: red;
			display: inline-block;
			margin-left: 1.5em;
		}
	</style>
</head>

<body>
<div class="wrapper wrapper-content animated fadeInRight">
	<div class="row">
		<div class="col-sm-12">
			<form class="form-horizontal" method="POST" id="addRole">
				<label><span class="text-danger">*</span>角色名称：</label>
				<input type="hidden" value="${roleId}" id="roleId">
				<input type="text" class="form-control" id="title" name="title" value="${role.title}" disabled>
				<br/>
				<label><span class="text-danger">*</span>角色权限：</label>
				<div id="tree"></div>
				<div class="pull-right">
					<button class="btn btn-success  radius" id="add" type="submit"><i class="icon-ok"></i> 确定
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<script src="${ctx}/js/jquery.min.js?v=2.1.4"></script>
<script src="${ctx}/js/bootstrap.min.js?v=3.3.6"></script>
<script src="${ctx}/js/bootstrap-treeview.min.js"></script>
<script src="${ctx}/js/plugins/layer/layer.js"></script>
<script src="${ctx}/js/plugins/validate/jquery.validate.min.js"></script>
<script src="${ctx}/js/plugins/validate/validate-methods.js"></script>
<script src="${ctx}/js/plugins/validate/jquery-form.js"></script>
<script src="${ctx}/js/plugins/validate/messages_zh.min.js"></script>
<script src="${ctx}/js/plugins/iCheck/icheck.min.js"></script>
<script type="text/javascript">
	$(document).ready(function () {
		var e = "<i class='fa fa-times-circle'></i> ";
		// 在键盘按下并释放及提交后验证提交表单
		var validator = $("#addRole").validate({
			submitHandler: function (form) {
				updateRole();
			},
			errorPlacement: function (error, element) {
				element.closest('#error').append(error);//显示错误消息提示
			},
			rules: {
				title: {
					remote: {
						url: "${ctx}/role/checkRoleExist", //后台处理程序
						type: "POST", //数据发送方式
						dataType: "JSON", //接受数据格式
						data: { //要传递的数据
							title: function () {
								return $("#title").val();
							}
						},
						dataFilter: function (data) {
							var result = eval("(" + data + ")");
							if (result.status == "1001") {
								return false;
							} else {
								return true;
							}
						}
					},
					required: true,
					minlength: 2
				}
			},
			messages: {
				title: {
					required: e + "请输入角色名",
					minlength: e + "角色名必需由两个字母以上组成",
					remote: e + "角色已存在"
				}
			}
		})

		function updateRole() {
			var roleId = $("#roleId").val();
			var a = $("#tree").treeview('getChecked');
			if (a == null || a.length <= 0) {
				layer.alert('权限不能为空!', {
					icon: 2,
					skin: 'layer-ext-moon'
				})
				return;
			}

			var permission = [];

			$(a).each(function () {
				if (this.id != 0 && this.id != null) {
					permission.push(this.id)
				}
			})
			var permissionIds = permission.join(",");
			$.ajax({
				url: "${ctx}/role/update",
				data: {"roleId":roleId,"permissionId": permissionIds},
				type: "PUT",
				dataType: "JSON",
				traditional: true,
				success: function (data) {
					if (data.status == "1000") {
						layer.alert('修改成功!', {
							icon: 1,
							skin: 'layer-ext-moon'
						},function(){
							setTimeout(function () {
								window.location.reload();
							}, 500);
						})
					} else if (data.status == "1001") {
						layer.alert('修改失败!', {
							icon: 2,
							skin: 'layer-ext-moon'
						})
						validator.resetForm();
					}
				}
			})

		}
	})

	$(document).ready(function () {
		var roleId = $("#roleId").val();
		$(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green",})
		$.ajax({
			url: "${ctx}/role/update/"+roleId,
			type: "GET",
			dataType: "JSON",
			success: function (data) {
				deleteEmptyProperty(data);
				$('#tree').treeview({
					data: data,
					showCheckbox: true,   //是否显示复选框
					highlightSelected: false,    //是否高亮选中
					multiSelect: true,    //多选
					levels: 5,
					enableLinks: false,//必须在节点属性给出href属性
					color: "#010A0E",
					'onNodeChecked': function (event, node) { //选中节点
						var selectNodes = getChildNodeIdArr(node); //获取所有子节点
						if (selectNodes) { //子节点不为空，则选中所有子节点
							$('#tree').treeview('checkNode', [selectNodes, {silent: true}]);
						}
						var parentNode = $("#tree").treeview("getNode", node.parentId);
						setParentNodeCheck(node);
					},
					'onNodeUnchecked': function (event, node) { //取消选中节点
						// 取消父节点 子节点取消
						var selectNodes = setChildNodeUncheck(node); //获取未被选中的子节点
						var childNodes = getChildNodeIdArr(node);    //获取所有子节点
						if (selectNodes && selectNodes.length == 0) { //有子节点且未被选中的子节点数目为0，则取消选中所有子节点
							$('#tree').treeview('uncheckNode', [childNodes, {silent: true}]);
						}
						// 取消节点 父节点取消
						var parentNode = $("#tree").treeview("getNode", node.parentId);  //获取父节点
						var selectNodes = getChildNodeIdArr(node);
						setParentNodeCheck(node);
					}
				});
			}
		})


	});


	// 选中父节点时，选中所有子节点
	function getChildNodeIdArr(node) {
		var ts = [];
		if (node.nodes) {
			for (x in node.nodes) {
				ts.push(node.nodes[x].nodeId);
				if (node.nodes[x].nodes) {
					var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
					for (j in getNodeDieDai) {
						ts.push(getNodeDieDai[j]);
					}
				}
			}
		} else {
			ts.push(node.nodeId);
		}
		return ts;
	}

	function setParentNodeCheck(node) {
		var parentNode = $("#tree").treeview("getNode", node.parentId);
		if (parentNode.nodes) {
			var checkedCount = 0;
			for (x in parentNode.nodes) {
				if (parentNode.nodes[x].state.checked) {
					checkedCount++;
				} else {
					break;
				}
			}
			if (checkedCount === parentNode.nodes.length) {
				$("#tree").treeview("checkNode", parentNode.nodeId);
				setParentNodeCheck(parentNode);
			}
		}
	}

	// 取消父节点时 取消所有子节点
	function setChildNodeUncheck(node) {
		if (node.nodes) {
			var ts = [];    //当前节点子集中未被选中的集合
			for (x in node.nodes) {
				if (!node.nodes[x].state.checked) {
					ts.push(node.nodes[x].nodeId);
				}
				if (node.nodes[x].nodes) {
					var getNodeDieDai = node.nodes[x];
					for (j in getNodeDieDai) {
						if (!getNodeDieDai.state.checked) {
							ts.push(getNodeDieDai[j]);
						}
					}
				}
			}
		}
		return ts;
	}

	function updateRole() {
		var roleId = $("#roleId").val();
		var exam = "";
		var paper = "";
		$("input[name='exam']:checked").each(function (i) {
			exam += ("," + $(this).val());
		})

		$("input[name='paper']:checked").each(function (i) {
			paper += ("," + $(this).val());
		});
		var permissionId = exam.concat(paper).split(",");
		for (var i = 0; i < permissionId.length; i++) {
			if (permissionId[i] == "" || typeof(permissionId[i]) == "undefined") {
				permissionId.splice(i, 1);
				i = i - 1;
			}
		}
		if (permissionId.length == 0) {
			layer.alert('权限不能为空!', {
				icon: 2,
				skin: 'layer-ext-moon'
			})
			return;
		}
		$.ajax({
			url: "${ctx}/role/update",
			data: {"roleId":roleId,"permissionId": permissionId},
			type: "PUT",
			dataType: "JSON",
			traditional: true,
			success: function (data) {
				if (data.status == "1000") {
					layer.alert('修改成功!', {
						icon: 1,
						skin: 'layer-ext-moon'
					},function(){
						setTimeout(function () {
							window.location.reload();
						}, 500);
					})
				} else if (data.status == "1001") {
					layer.alert('修改失败!', {
						icon: 2,
						skin: 'layer-ext-moon'
					})
					validator.resetForm();
				}
			}
		})

	}

	function deleteEmptyProperty(object){
		for (var i in object) {
			var value = object[i];
			if (typeof value === 'object') {
				if (Array.isArray(value)) {
					if (value.length == 0) {
						delete object[i];
						continue;
					}
				}
				this.deleteEmptyProperty(value);
				if (this.isEmpty(value)) {
					delete object[i];
				}
			} else {
				if (value === '' || value === null || value === undefined) {
					delete object[i];
				} else {
				}
			}
		}
	}

	function isEmpty(object) {
		for (var name in object) {
			return false;
		}
		return true;
	}
</script>
</body>

</html>